﻿using System.Xml;
using VASJ.Common;
using VASJ.Model;

namespace VASJ.Model
{
    public class ConfigManager
    {
        public static Configuration ConfigurationInstant;

        public static void Run()
        {
            #region Configuration

            ConfigManager.ConfigurationInstant = SerializationTool<Configuration>.Load(Constants.PathCommonLocation);

            if (ConfigManager.ConfigurationInstant == null)
            {
                SerializationTool<Configuration>.Save(Constants.PathCommonLocation, new Configuration());

                ConfigManager.SaveWithEndcoding();

                ConfigManager.ConfigurationInstant = SerializationTool<Configuration>.Load(Constants.PathCommonLocation);
            }

            #endregion Configuration
        }

        public static void SaveWithEndcoding()
        {
            string filename = Constants.PathCommonLocation + Constants.CONFIGURATION_FILE_NAME;

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(filename);

            XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
            {
                xmlDoc.ReplaceChild(xmlDecl, xmlDoc.FirstChild);
            }
            else
            {
                xmlDoc.InsertBefore(xmlDecl, xmlDoc.DocumentElement);
            }

            xmlDoc.Save(filename);
        }

        public static void Save()
        {
            if (ConfigManager.ConfigurationInstant != null)
            {
                SerializationTool<Configuration>.Save(Constants.PathCommonLocation, ConfigManager.ConfigurationInstant);
                SaveWithEndcoding();
            }
        }
    }
}